import React, { FC, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Mask, InfiniteScroll } from 'antd-mobile'
import Header from '@/components/home/header'
import Loading from '@/components/home/loading/saleLoading'
import ChangeDropdown from '@/components/changeCourse/changeDropdown'
import ChangeRule from '@/components/changeCourse/changeRule'
import Course from '@/components/changeCourse/course'
import BtnGroup from '@/components/changeCourse/btnGroup'
import PopupSection from '@/components/changeCourse//popupSection'
import EmptyChange from '@/components/changeCourse/empty'
import CourseDialog from '@/components/changeCourse/courseDialog'
import { getQueryVariable } from '@/utils/http'
import { getcourseplanlist, getIdencode } from '@/api/changeCourse'
import { CourseplanData, adjustKeys, ConditionItem, CourseListItem } from '@/types/changeCourse'
import leftOrangeIcon from '@/assets/images/right_orange_icon.png'

const changeCourseList: FC<{}> = () => {
  const stuCouId = getQueryVariable('stuCouId')
  const courseId = getQueryVariable('courseId')
  const adjustType = getQueryVariable('adjustType')
  const navigate = useNavigate()
  if (!(stuCouId && courseId && adjustType)) {
    navigate('/404')
    return <></>
  }
  const [loading, setLoading] = useState<boolean>(false)
  const [couresPlanData, setCoursePlanData] = useState<Partial<CourseplanData>>()
  const [modalContentBtn, setModalContentBtn] = useState<
    Partial<{
      list: ConditionItem[] | null
      value: ConditionItem | null
    }>
  >({})
  const [selectItem, setSelectItem] = useState<{ [key: string]: ConditionItem }>({})
  const [checkedItem, setCheckedItem] = useState<Partial<CourseListItem>>({})
  const [num, setNum] = useState<number>(1)
  const [show, setShow] = useState<boolean>(false)
  const [visible, setVisible] = useState<boolean>(false)
  const [hasMore, setHasMore] = useState<boolean>(true)
  const [dialogVisible, setDialogVisible] = useState<boolean>(false)
  const dropDownData = adjustKeys[adjustType].dropDown
  const modalContent = adjustKeys[adjustType].modalContent
  const getData = async (condition: { [key: string]: string }, pageNum: number, init?: boolean) => {
    setLoading(true)
    await getcourseplanlist({
      courseId: courseId,
      stuCouId: stuCouId,
      adjustType: adjustType,
      condition: JSON.stringify(condition),
      pageNum: pageNum + '',
      pageSize: '20',
    }).then((res) => {
      setLoading(false)
      if (res.stat == 1 && res.msg == 'success') {
        const data = res.data
        const newData = { ...data }
        newData.courseList = (couresPlanData?.courseList || []).concat(data.courseList)
        setCoursePlanData(newData)
        setNum(parseInt(data.pageNum))
        setHasMore(data.total > parseInt(data.pageSize) * parseInt(data.pageNum))
        if (init) {
          const keyName = modalContent.value
          const list = data.condition[keyName as keyof typeof data.condition]
          const course = data.stuCouInfo.course
          setShow(!!(modalContent.show && list && list.length > 0 && data.courseList.length > 0))
          let objectparam: ConditionItem[] = []
          switch (adjustType) {
            case 'adjustDiff':
              objectparam = list?.filter((val) => parseInt(val.id) == course.difficulty.id) || []
              break
            case 'adjustVersion':
              objectparam = list?.filter((val) => val.id == course.versionID) || []
              break
            case 'adjustGrader':
              objectparam = list?.filter((val) => val.id == course.gradeIds) || []
              break
            case 'adjustLevel':
              objectparam = list?.filter((val) => val.id == course.learningStage) || []
              break
            default:
              objectparam = []
          }
          setModalContentBtn({
            list: list || [],
            value: objectparam[0] || null,
          })
          // if (objectparam[0]) {
          //   console.log({ [modalContent.value]: objectparam[0] })
          //   setSelectItem({ [modalContent.value]: objectparam[0] })
          // }
        }
      }
    })
  }
  const getCourseIdFun = (e: React.BaseSyntheticEvent, item: CourseListItem) => {
    e.stopPropagation()
    if (checkedItem.course?.id && item.course.id == checkedItem.course.id) {
      setCheckedItem({})
    } else {
      setCheckedItem(item)
    }
  }
  const selectItemFun = (item: { [key: string]: ConditionItem }) => {
    setShow(false)
    setSelectItem({ ...item })
    const condition: { [key: string]: string } = {}
    Object.keys(item).forEach((val) => {
      condition[val] = item[val].id
    })
    getData({ ...condition }, 1)
  }
  const loadMore = async () => {
    const condition: { [key: string]: string } = {}
    Object.keys(selectItem).forEach((val) => {
      condition[val] = selectItem[val].id
    })
    getData({ ...condition }, num + 1)
  }
  const nextPath = () => {
    if (checkedItem?.exam?.type == 2) {
      window.location.href = checkedItem.exam.examUrl
    } else {
      if (checkedItem.coursePlanConsume && checkedItem.coursePlanConsume > 0) {
        setDialogVisible(true)
      } else {
        jumpTo()
      }
    }
  }
  const jumpTo = () => {
    getIdencode({
      adjustType: adjustType,
      stuCouId: stuCouId,
      originalCourseId: couresPlanData?.stuCouInfo?.course.id,
      originalClassId: couresPlanData?.stuCouInfo?.class.classId,
      targetClassId: checkedItem.class?.classId,
      targetCourseId: checkedItem.course?.id,
      diffType: checkedItem.diffPriceInfo?.diffType,
    }).then((res) => {
      if (res.stat === 1) {
        navigate('/confirm?idEncode=' + res.data.idEncode)
      }
    })
  }
  useEffect(() => {
    getData({}, 1, true)
  }, [])
  return (
    <div className="w-full h-full min-h-screen bg-gray-F7F7F8 font-normal font-regular">
      <Header
        cb={() => {
          navigate(-1)
        }}
        headerText={'选择新课程'}
        headerColor="bg-white"
        notHeaderColor={false}
      ></Header>
      {loading ? <Loading noBorder={true} modal={true}></Loading> : null}
      <ChangeRule />
      {couresPlanData ? (
        <>
          <ChangeDropdown
            downItem={dropDownData || []}
            data={couresPlanData.condition || {}}
            defaultItem={selectItem}
            setSelectItem={(item: { [key: string]: ConditionItem }) => selectItemFun(item)}
          ></ChangeDropdown>
          {couresPlanData.courseList && couresPlanData.courseList?.length > 0 ? (
            <>
              <div className="px-r1.2 pt-r1.2" style={{ backgroundImage: leftOrangeIcon }}>
                {couresPlanData.courseList.map((val: CourseListItem, index: number) => (
                  <div
                    key={index}
                    className="bg-white mb-r1.0 rounded-r0.8"
                    onClick={(e) => {
                      e.stopPropagation()
                      window.location.href = val.courseUrl
                    }}
                  >
                    <div className="flex px-r1.2 py-r1.6">
                      <div
                        className="flex items-center pr-r1.2"
                        onClick={(e) => getCourseIdFun(e, val)}
                      >
                        {checkedItem?.course?.id == val.course.id ? (
                          <i className="w-r1.6 h-r1.6 text-r1.6 leading-r1.6 iconfont icon-icon_selected"></i>
                        ) : (
                          <i className="w-r1.6 h-r1.6 text-r1.6 leading-r1.6 iconfont icon-icon_unselected"></i>
                        )}
                      </div>
                      <div className="relative">
                        {val.coursePlanConsume > 0 && (
                          <div className="text-red-FF3627 text-r1.2 leading-r1.2 mb-r1.2">
                            已开课{val.coursePlanConsume}讲 可观看回放
                          </div>
                        )}
                        <Course
                          course={val}
                          left={val.diffPriceInfo.diffType == 1 || val.diffPriceInfo.diffType == 2}
                        ></Course>
                        {(val.diffPriceInfo.diffType == 1 || val.diffPriceInfo.diffType == 2) && (
                          <div className="absolute right-r1.2 bottom-0 h-r1.6 z-10 text-red-FF3627 text-r1.2 leading-r1.6">
                            {val.diffPriceInfo.diffType == 1 && '补差价'}
                            {val.diffPriceInfo.diffType == 2 && '退回'}
                            <span className="ml-r0.2 mr-r0.2">¥</span>
                            <span className="font-semibold text-r1.6 leading-r1.6">
                              {val.diffPriceInfo.diffPrice}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                    {val.exam.type == 2 && (
                      <div className="pl-r4.0 pr-r1.2 pb-r1.6 ">
                        <div
                          className=" h-r2.8 leading-r2.8 bg-gray-333333 rounded-r0.4 pl-r0.8 pr-r0.9 text-r1.2 text-orange-BE8243 relative"
                          style={{ background: 'linear-gradient(to right,#FFF1DC,#FFFFFF)' }}
                          onClick={(e) => {
                            e.stopPropagation()
                            window.location.href = val.exam.examUrl
                          }}
                        >
                          该课程需诊断报名
                          <div className="absolute leading-r1.6 h-r1.6 right-r0.8 top-r0.6">
                            <img alt="" src={leftOrangeIcon} className="w-r1.6  h-auto m-auto" />
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
              <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={0} />
            </>
          ) : (
            <EmptyChange style={{ marginTop: '8rem' }} content={['暂无可以调入的课程']} />
          )}
          <BtnGroup
            text={checkedItem?.exam?.type == 2 ? '去诊断' : '下一步'}
            showLeft={true}
            leftContent={
              <div className="h-r4.0 mr-r1.8" onClick={() => setVisible(true)}>
                <div className="h-r2.8 leading-r2.8 text-center">
                  <i className="h-r2.8 w-r2.8 text-r2.8 iconfont icon-icon_course text-gray-999999"></i>
                </div>
                <div className="scale-50 w-r6.0  origin-center text-r2.0 leading-r2.0 -mt-r0.5 -mx-r1.5 text-gray-999999">
                  原课程
                </div>
              </div>
            }
            disabled={!checkedItem?.course?.id}
            loading={false}
            btnClick={() => nextPath()}
          ></BtnGroup>
          <PopupSection
            visible={visible}
            title="原课程信息"
            content={
              <div className="border border-white-F3F3F4 border-r0.1 rounded-r0.8">
                {couresPlanData?.stuCouInfo && (
                  <Course
                    course={couresPlanData?.stuCouInfo}
                    className="px-r1.2 pt-r1.6 pb-r1.6"
                  ></Course>
                )}
              </div>
            }
            changeVisible={(status: boolean) => setVisible(status)}
          ></PopupSection>
          <CourseDialog
            visible={dialogVisible}
            title="是否继续调课"
            content={
              '请谨慎操作！该课程已上过' +
              checkedItem.coursePlanConsume +
              '讲，历史讲次知能回放，不可以看直播。'
            }
            confirmText="继续"
            onCancel={() => setDialogVisible(false)}
            onConfirm={() => jumpTo()}
          ></CourseDialog>
          <Mask visible={show}>
            <div className="absolute left-r3.4 right-r3.4 top-1/2 -translate-y-1/2">
              <div className="p-r2.0 relative bg-white rounded-r1.2">
                <div
                  className="absolute right-r2.0 top-r2.0 text-r0.0 leading-r1.6 h-r1.6"
                  onClick={() => navigate('/changeCourseType?stuCouId=' + stuCouId)}
                >
                  <i className="h-r1.6 text-r1.6 iconfont icon-icon_colse"></i>
                </div>
                <div className="text-gray-333333 text-r1.6 leading-r2.4 mt-r0.3 text-center font-medium-family mx-r2.0">
                  选择要调换的新课程{modalContent.name}
                </div>
                <div className="text-gray-666666 text-r1.3 leading-r1.6 mt-r0.6 text-center">
                  原课程{modalContent.name}：{modalContentBtn?.value?.name || ''}
                </div>
                <div className="flex flex-wrap justify-between max-h-r40.0 overflow-auto -mx-r0.6 mt-r2.2">
                  {modalContentBtn?.list && modalContentBtn?.list.length > 0 ? (
                    <>
                      {modalContentBtn?.list.map((val: ConditionItem, index: number) => (
                        <div
                          key={index}
                          className="px-r0.6 pb-r1.2 w-1/2"
                          onClick={() => selectItemFun({ [modalContent.value]: val })}
                        >
                          <div
                            className={
                              'text-center px-r0.4 rounded-r2.0 h-r4.0 text-r1.2 leading-r4.0 truncate ' +
                              (selectItem[modalContent.value] &&
                              selectItem[modalContent.value].id == val.id
                                ? 'text-red-FF3627 bg-red-FF3627 bg-opacity-10 font-medium-family'
                                : ' text-gray-333333 bg-gray-F7F7F8')
                            }
                          >
                            {val.name}
                          </div>
                        </div>
                      ))}
                    </>
                  ) : (
                    ''
                  )}
                </div>
              </div>
            </div>
          </Mask>
        </>
      ) : (
        <>
          <EmptyChange style={{ marginTop: '8rem' }} content={['暂无可以调入的课程']} />
        </>
      )}
    </div>
  )
}

export default changeCourseList
